package br.com.sitran.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.sitran.util.JPAUtil;



public abstract class GenericDao<T> {
	
	public void persit(T instance){
		EntityManager em = JPAUtil.getInstance().getEntityManager();
		try{
			
			em.getTransaction().begin();
			em.persist(instance);
			em.getTransaction().commit();
		}catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		}finally{
			em.close();
		}
		
	}
	
	public void delete(T instance){
		EntityManager em = JPAUtil.getInstance().getEntityManager();
		try{
			
			em.getTransaction().begin();
			T instancedelete = em.merge(instance);
			em.remove(instancedelete);
			em.getTransaction().commit();
		}catch (Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		}finally{
			em.close();
		}
	}
	
	public void update(T instance){
		EntityManager em = JPAUtil.getInstance().getEntityManager();
		try{
			
			em.getTransaction().begin();
			em.merge(instance);
			em.getTransaction().commit();
		}catch (RuntimeException e) {
			e.printStackTrace();
			em.getTransaction().rollback();
		}finally{
			em.close();
		}
		
		
	}
	
	@SuppressWarnings("hiding")
	public <T> T findById(Class<T> instance,Integer id){
		EntityManager em = JPAUtil.getInstance().getEntityManager();
		try{
			em.getTransaction().begin();
			T retorno = em.find(instance, id);
			em.getTransaction().commit();
			return retorno;
		}catch (RuntimeException e) {
			e.printStackTrace();
			em.getTransaction().rollback();
			throw e;
		}finally{
			em.close();
		}
		
	}
	
	 public List<T>  getList(Class<T> instance){
		 EntityManager em = JPAUtil.getInstance().getEntityManager();
		 try{
			 em.getTransaction().begin();
			 List<T> retorno = em.createQuery("select e from " + instance.getName()+" e").getResultList();
			 em.getTransaction().commit();
			 return retorno;
		 }catch (RuntimeException e) {
			e.printStackTrace();
			em.getTransaction().rollback();
			throw e;
		}finally{
			
			em.close();
			
		}
		
		
		
		 
	 }   
	
	
	
	
}
